/*
 * @Author: szx
 * @Date: 2022-02-26 13:14:03
 * @LastEditTime: 2022-02-26 14:32:09
 * @Description:
 * @FilePath: \leetcode\600-699\658\658.js
 */
/**
 * @param {number[]} arr
 * @param {number} k
 * @param {number} x
 * @return {number[]}
 */

var findClosestElements = function (arr, k, x) {
    let l = 0,
        r = arr.length - 1;
    while (r - l + 1 > k) {
        const l_dis = x - arr[l];
        const r_dis = arr[r] - x;
        if (r_dis >= l_dis) r--;
        else l++;
    }
    return arr.slice(l, r + 1);
};

var findClosestElements = function (arr, k, x) {
    let index = find(arr, x);
    if(index>0 && x - arr[index-1] <= arr[index] - x)index--;
    if(index<arr.length-1 && x- arr[index] > arr[index+1] - x) index++

    let l = index-1;
    let r = index+1;
    while (r - l -1 < k) {
        if (l < 0) {
            r++;
            continue;
        }
        if (r >= arr.length) {
            l--;
            continue;
        }
        if (x - arr[l] <= arr[r] - x) l--;
        else r++;
    }
    return arr.slice(l+1, r);
};
const find = (arr, x) => {
    let l = 0,
        r = arr.length - 1;
    while (l < r) {
        const mid = Math.floor((r + l) / 2);
        if (arr[mid] > x) r = mid - 1;
        else if (arr[mid] == x) {
            return mid;
        } else l = mid + 1;
    }
    return l;
};


console.log(findClosestElements([1, 2, 3, 4, 5], 4, -1));
